<?php
namespace api\modules\v1\models;

use api\components\ApiModel;
use api\components\RuleUtil;
use common\models\ARBrokerAmount;
use common\models\ARCoinType;
use common\models\ARLoginHistory;
use common\models\ARUser;
use common\models\ARUserCertificate;
use common\models\ARUserConfig;
use common\models\ARUserScoring;
use common\models\Certificate;
use common\models\Message;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 用户模型
 * @author
 */
class UserInfo extends ApiModel
{
    const SCENARIO_USER_REGISTER = 'user_register';
    const SCENARIO_USER_LOGIN = 'user_login';
    const SCENARIO_ADMIN_LOGIN = 'admin_login';
    const SCENARIO_LOGIN_HISTORY = 'login_history';
    const SCENARIO_PASSWORDEDIT = 'editpassword';
    const SCENARIO_EDITEMAIL = 'editemail';
    const SCENARIO_EDITMOBILE = 'editmobile';
    const SCENARIO_SETEMAIL = 'setemail';
    const SCENARIO_SETMOBILE = 'setmobile';
    const SCENARIO_SETPAYWORD = 'setpayword';
    const SCENARIO_PAYWORDEDIT = 'editpayword';
    const SCENARIO_SETPASSWORD = 'setpassword';
    const SCENARIO_RESETPASSWORD = 'resetpassword';

    const SCENARIO_PLATFORM = 'platform';
    const SCENARIO_SYSTEM = 'System';

    const SCENARIO_CERTIFICATE = 'certificate';

    const ROLE_MEMBER = 'Member';
    const ROLE_PLATFORM = 'Platform';
    const ROLE_SYSTEM = 'System';

    public $nickname;
    public $username;
    public $account;
    public $password;
    public $repassword;
    public $payword;
    public $repayword;
    public $mobile;
    public $email;
    public $country;
    public $provinces;
    public $code;
    public $old_password;
    public $old_payword;
    public $instructionId;
    public $signature;
    public $new_address;
    public $new_email;
    public $new_code;
    public $mode;
    public $new_mobile;
    public $new_country;
    public $token;
    public $page;
    public $size;

    public $real_name;
    public $certificate_type;
    public $certificate_number;
    public $image_mid;
    public $image_mid_hand;
    public $thumb_image;
    public $thumb_image_hand;

    private $accountType;

    protected $_user;
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'nickname'           => '昵称',
            'username'           => '用户名',
            'account'            => '用户账号',
            'password'           => '登录密码',
            'repassword'         => '确认登陆密码',
            'payword'            => '交易密码',
            'repayword'          => '确认交易密码',
            'mobile'             => '手机',
            'email'              => '邮箱',
            'country'            => '国家',
            'provinces'          => '省份',
            'code'               => '验证码',
            'old_password'       => '原登录密码',
            'instructionId'      => '操作回执',
            'signature'          => '操作签名',
            'new_address'        => '新地址',
            'new_email'          => '新邮箱',
            'new_code'           => '新验证码',
            'mode'               => '消息方式',
            'new_mobile'         => '新手机号码',
            'new_country'        => '新手机所属国家',
            'old_payword'        => '原交易密码',
            'token'              => '设置登录密码token值',
            'real_name'          => '真实姓名',
            'certificate_type'   => '证件类型',
            'certificate_number' => '证件号码',
            'image_mid'          => '证件图片id',
            'image_mid_hand'     => '手持证件图片id',
            'thumb_image'        => '证件图片路径',
            'thumb_image_hand'   => '手持证件图片路径',
            'page'               => '当前页',
            'size'               => '分页大小',
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_USER_REGISTER => ['nickname', 'password', 'repassword', 'account', 'code', 'mode', 'country'],
            self::SCENARIO_USER_LOGIN    => ['account', 'password'],
            self::SCENARIO_ADMIN_LOGIN   => ['username', 'password'],
            self::SCENARIO_LOGIN_HISTORY => ['page', 'size'],
            self::SCENARIO_PASSWORDEDIT  => ['old_password', 'password', 'repassword', 'instructionId', 'signature', 'new_address'],
            self::SCENARIO_EDITEMAIL     => ['code', 'new_email', 'new_code'],
            self::SCENARIO_EDITMOBILE    => ['code', 'new_country', 'new_mobile', 'new_code'],
            self::SCENARIO_SETEMAIL      => ['email', 'code'],
            self::SCENARIO_SETMOBILE     => ['country', 'mobile', 'code'],
            self::SCENARIO_SETPAYWORD    => ['code', 'payword', 'repayword', 'mode'],
            self::SCENARIO_PAYWORDEDIT   => ['old_payword', 'payword', 'repayword'],
            self::SCENARIO_SETPASSWORD   => ['email', 'password', 'repassword', 'token'],
            self::SCENARIO_PLATFORM      => ['username', 'password', 'repassword'],
            self::SCENARIO_SYSTEM        => ['username', 'password', 'repassword'],
            self::SCENARIO_RESETPASSWORD => ['mobile', 'country', 'password', 'repassword', 'code'],
            self::SCENARIO_CERTIFICATE   => ['real_name', 'certificate_type', 'certificate_number', 'image_mid', 'image_mid_hand', 'country', 'provinces'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nickname', 'username', 'account', 'password', 'repassword', 'payword', 'repayword', 'mobile', 'email', 'country', 'code', 'new_address', 'new_email', 'new_code', 'real_name', 'certificate_type', 'certificate_number', 'image_mid', 'image_mid_hand'], 'trim'],
            [['nickname', 'username', 'account', 'password', 'old_password', 'old_payword', 'repassword', 'code', 'payword', 'repayword', 'signature', 'instructionId', 'new_address', 'new_email', 'new_code', 'new_mobile', 'token', 'real_name', 'certificate_type', 'certificate_number', 'image_mid', 'image_mid_hand'], 'required'],
            ['account', 'accountTypeCheck', 'on' => [self::SCENARIO_USER_LOGIN]],
            ['mode', 'default', 'value' => 'email'],
            ['mode', 'in', 'range' => [Message::MODE_SMS, Message::MODE_EMAIL]],
            ['account', 'verifyMobile', 'when' => function ($model) {
                return $this->mode === Message::MODE_SMS;
            }],
            ['account', 'email', 'when' => function ($model) {
                return $this->mode === Message::MODE_EMAIL;
            }],
            ['account', 'accountCheck', 'on' => [self::SCENARIO_USER_REGISTER]],
            ['username', 'unique', 'targetClass' => 'common\models\ARUser', 'targetAttribute' => 'username', 'on' => [self::SCENARIO_PLATFORM, self::SCENARIO_SYSTEM]],
            ['username', 'usernameCheck', 'on' => [self::SCENARIO_ADMIN_LOGIN]],
            ['email', 'required', 'on' => [self::SCENARIO_SETEMAIL, self::SCENARIO_SETPASSWORD]],
            ['mobile', 'required', 'on' => [self::SCENARIO_SETMOBILE]],
            ['password', 'string', 'length' => [6, 24]],
            ['password', 'compare', 'compareAttribute' => 'repassword', 'on' => [self::SCENARIO_USER_REGISTER, self::SCENARIO_PASSWORDEDIT, self::SCENARIO_SETPASSWORD]],
            ['payword', 'match', 'pattern' => '/^[0-9]{6}$/'],
            [['code', 'new_code'], 'string', 'length' => 6],
            [['mobile', 'new_mobile'], 'verifyMobile'],
            [['mobile', 'new_mobile'], 'mobileStatusCheck', 'on' => [self::SCENARIO_EDITMOBILE, self::SCENARIO_SETMOBILE]],
            [['mobile', 'new_mobile'], 'mobileCheck', 'on' => [self::SCENARIO_EDITMOBILE, self::SCENARIO_SETMOBILE]],
            [['email', 'new_email'], 'email'],
            [['email', 'new_email'], 'emailStatusCheck', 'on' => [self::SCENARIO_EDITEMAIL, self::SCENARIO_SETEMAIL]],
            [['email', 'new_email'], 'emailCheck', 'on' => [self::SCENARIO_EDITEMAIL, self::SCENARIO_SETEMAIL]],
            ['country','required','on' => [self::SCENARIO_CERTIFICATE]],
            ['provinces', 'required', 'when' => function ($model) {
                return strtoupper($this->country) ==='CN';
            }],
            ['provinces','checkProvicnce'],
            [['country', 'new_country'], 'default', 'value' => 'CN'],
            [['country', 'new_country'], 'checkCountry'],
            ['password', 'validatePassword', 'on' => [self::SCENARIO_USER_LOGIN, self::SCENARIO_ADMIN_LOGIN]],
            ['old_password', 'oldPasswordCheck'],
            ['new_address', 'string', 'length' => 64],
            ['nickname', 'unique', 'targetClass' => 'common\models\ARUser', 'targetAttribute' => 'nickname'],
            ['payword', 'match', 'pattern' => '/^[0-9]{6}$/'],
            ['payword', 'compare', 'compareAttribute' => 'repayword'],
            ['old_payword', 'oldPaywordCheck'],
            ['page', 'default', 'value' => 1],
            ['size', 'default', 'value' => 5],
            ['certificate_type','checkCardType'],
            ['certificate_number','checkCardNum'],
            
            
        ];
    }

    /**
     * 手机号格式检验
     */
    public function verifyMobile($attribute, $params)
    {
        $res = RuleUtil::checkMobile($this->$attribute);
        if (!$res) {
            $this->addError($attribute, '手机号格式不正确');
        }
    }

    /**
     * 用户注册账号检测
     */
    public function accountCheck($attribute, $params)
    {
        if ($this->mode == Message::MODE_SMS) {
            $userInfo = ARUser::findOne(['mobile' => $this->$attribute]);
        } else {
            $userInfo = ARUser::findOne(['email' => $this->$attribute]);
        }
        if ($userInfo) {
            $this->addError($attribute, '该账号已经被注册');
        }

    }

    /**
     * 用户手机状态校验器
     */
    public function mobileStatusCheck($attribute, $params)
    {
        $user = $this->getUser();
        $scenario = $this->getScenario();
        if (null === $user->mobile && $scenario == self::SCENARIO_EDITMOBILE) {
            $this->addError($attribute, '用户未绑定手机号码');
        } elseif ($user->mobile && $scenario == self::SCENARIO_SETMOBILE) {
            $this->addError($attribute, '用户已绑定手机号码');
        }
    }

    /**
     * 手机号码校验器
     */
    public function mobileCheck($attribute, $params)
    {
        $userInfo = ARUser::findOne(['mobile' => $this->$attribute]);
        $scenario = $this->getScenario();
        if (null != $userInfo) {
            if ($scenario == self::SCENARIO_EDITMOBILE) {
                $user = $this->getUser();
                if ($userInfo->id == $user->id) {
                    $this->addError($attribute, '新手机号码和原手机号码相同');
                } else {
                    $this->addError($attribute, '新手机号码已绑定其他账号');
                }
            } else {
                $this->addError($attribute, '该手机号已绑定其他账号');
            }
        }
    }

    /**
     * 邮箱状态校验器
     */
    public function emailStatusCheck($attribute, $params)
    {
        $user = $this->getUser();
        $scenario = $this->getScenario();
        if (null === $user->email && $scenario == self::SCENARIO_EDITEMAIL) {
            $this->addError($attribute, '用户未绑定邮箱');
        } elseif ($user->email && $scenario == self::SCENARIO_SETEMAIL) {
            $this->addError($attribute, '用户已绑定邮箱');
        }
    }

    /**
     * 邮箱验证器
     */
    public function emailCheck($attribute, $params)
    {
        $userInfo = ARUser::findOne(['email' => $this->$attribute]);
        $scenario = $this->getScenario();
        if (null != $userInfo) {
            if ($scenario == self::SCENARIO_EDITEMAIL) {
                $user = $this->getUser();
                if ($userInfo->id == $user->id) {
                    $this->addError($attribute, '新邮箱和原邮箱相同');
                } else {
                    $this->addError($attribute, '新邮箱已绑定其他账号');
                }
            } else {
                $this->addError($attribute, '邮箱已绑定其他账号');
            }
        }
    }

    /**
     * 密码校验器
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->_user == null) {
                self::throwError('100021');
            }
            if (!$this->_user->validatePassword($this->password)) {
                $this->addError($attribute, '账户和密码不匹配。');
            }
        }
    }

    /**
     * 账号类型校验器
     */
    public function accountTypeCheck($attribute, $params)
    {
        $email_regexp = '/^((?:"?([^"]*)"?\s)?)(?:\s+)?(?:(<?)((.+)@([^>]+))(>?))$/';
        preg_match($email_regexp, $this->account, $email_match);
        if ($email_match) {
            //邮箱格式
            $accountType = Message::MODE_EMAIL;
        } else {
            $res = RuleUtil::checkMobile($this->account);
            if ($res) {
                //手机号格式
                $accountType = Message::MODE_SMS;
            }
        }
        if (!isset($accountType)) {
            self::throwError('100023'); //格式错误
        }
        if ($accountType == Message::MODE_EMAIL) {
            $user = ARUser::findByEmail($this->account);
        } else {
            $user = ARUser::findByMobile($this->account);
        }
        if (!$user) {
            self::throwError('100021');
        } else {
            $this->accountType = $accountType;
            $this->_user = $user;
        }
    }

    /**
     * 用户名校验器
     */
    public function usernameCheck($attribute, $params)
    {
        $user = ARUser::findByUsername($this->username);
        if (!$user) {
            self::throwError('100021');
        } else {
            $this->_user = $user;
        }
    }

    /**
     * 原密码校验器
     */
    public function oldPasswordCheck($attribute, $params)
    {
        $user = $this->getUser();
        if (!$user->validatePassword($this->$attribute)) {
            $this->addError($attribute, '原密码不正确');
        } elseif ($this->$attribute === $this->password) {
            $this->addError($attribute, '新密码和和旧密码相同');
        }
    }

    /**
     * 原交易密码校验器
     */
    public function oldPaywordCheck($attribute, $params)
    {
        $user = $this->getUser();
        if (!$user->validatePayword($this->$attribute)) {
            $this->addError($attribute, '原交易密码不正确');
        } elseif ($this->$attribute === $this->payword) {
            $this->addError($attribute, '新交易密码和和旧交易密码相同');
        }
    }
    
    
    /**
     * 证件类型检测
     */
    public function checkCardType($attribute, $params)
    {
        $cardTypes=Yii::$app->params['cardType'];
        if(!isset($cardTypes[$this->$attribute])){
            $this->addError($attribute,'证件类型无效');
        }
    }
    
    /**
     * 证件号码检测
     */
    public function checkCardNum($attribute, $params){
        if($this->certificate_type==1){
            $res = RuleUtil::checkIdNum($this->$attribute);
            if (!$res) {
                $this->addError($attribute, '证件号格式不正确');
            }
        }
    }
    
    /**
     * 国家校验
     */
    public function checkCountry($attribute,$params){
        list($res,$data)=RuleUtil::checkCountry($this->$attribute);
        if(!$res){
            $this->addError($attribute,'国家名称不合法');
        }
    }
    
    
    /**
     * 省份检测
     * @param unknown $attribute
     * @param unknown $params
     */
    public function checkProvicnce($attribute,$params){
        if(strtoupper($this->country)==='CN'){
            list($res,$data)=RuleUtil::checkProvince($this->$attribute);
            if(!$res){
                $this->addError($attribute,'省份名称不合法');
            }
        }
         
    }
    
    /**
     * 用户注册
     */
    public function register()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        //邮箱验证码验证
        if ($this->mode == Message::MODE_EMAIL) {
            list($flag, $data) = Message::validateEmailCode('binding', $this->code, $this->account);
            if (!$flag) {
                self::throwError('100011');
            }
        } else {
            list($flag, $data) = Message::validateMobileCode('binding', $this->code, $this->account, $this->country);
            if (!$flag) {
                self::throwError('100012');
            }
        }

        $user = new ARUser();
        if ($this->mode == Message::MODE_EMAIL) {
            $user->username = Yii::$app->params['modeType']['email'] . $this->account;
            $user->email = $this->account;
        } else {
            $user->username = Yii::$app->params['modeType']['sms'] . $this->account;
            $user->mobile = $this->account;
            $user->mobile_country = $this->country;
        }
        $user->nickname = $this->nickname;
        $user->setPassword($this->password);
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                self::getErrorMessge($user);
            }
            $roleInfo = Yii::$app->authManager->getRole(self::ROLE_MEMBER);
            if (empty($roleInfo)) {
                self::throwError('200002');
            }
            $auth = Yii::$app->authManager->assign($roleInfo, $user->id);
            if (!$auth) {
                self::throwError('200003');
            }
            //新增用户配置表记录
            $userconfig = new ARUserConfig();
            $userconfig->uid = $user->id;
            if ($this->mode == Message::MODE_EMAIL) {
                $userconfig->is_email = ARUserConfig::STATUS_BIND;
            } else {
                $userconfig->is_mobile = ARUserConfig::STATUS_BIND;
            }
            if (!$userconfig->save()) {
                self::getErrorMessge($userconfig);
            }

            //新增用户评分表记录
            $userscoring = new ARUserScoring();
            $userscoring->uid = $user->id;
            if (!$userscoring->save()) {
                self::getErrorMessge($userscoring);
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
        return ['userId' => $user->id, 'username' => $user->username];
    }

    /**
     * 用户登陆
     */
    public function login()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }

        $params = [
            'client_id'     => Yii::$app->params['auth_info']['client_id'],
            'client_secret' => Yii::$app->params['auth_info']['client_secret'],
            'grant_type'    => Yii::$app->params['auth_info']['grant_type'],
            'password'      => $this->password,
        ];
        if ($this->getScenario() == self::SCENARIO_ADMIN_LOGIN) {
            $params['username'] = $this->username;
        } else {
            if ($this->accountType == Message::MODE_EMAIL) {
                $params['email'] = $this->account;
            } else {
                $params['mobile'] = $this->account;
            }
        }
        $url = isset(Yii::$app->params['oauth_login_url']) ? Yii::$app->params['oauth_login_url'] : Yii::$app->request->hostInfo . Yii::$app->params['auth_info']['url'];
        $result = $this->curl($url, $params);
        if ($result['success']) {
            $tran = Yii::$app->db->beginTransaction();
            try {
                $time = Yii::$app->formatter->asTimestamp('now');
                $this->_user->lastlogin_at = $time;
                $this->_user->update();

                //记录登陆历史
                $history = new ARLoginHistory();
                $history->uid = $this->_user->id;
                $history->ip = Yii::$app->request->userIP;
                $history->login_at = $time;
                $history->place = self::getIpPlace($history->ip);
                $history->save();

                $tran->commit();
                return ['data' => $result['data'], 'type' => $this->accountType, 'nickname' => $this->_user->nickname];
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        } else {
            self::throwError('100022');
        }
    }

    /**
     * 获取真实姓名
     */
    public function getUserName()
    {
        $user_certificate = ARUserCertificate::findOne(['uid' => Yii::$app->user->id]);
        return ['name' => ($user_certificate) ? $user_certificate->real_name : null];
    }

    /**
     * 获取用户信息
     */
    public function getUserData()
    {
        $user_certificate = ARUserCertificate::findOne(['uid' => Yii::$app->user->id]);
        $data = [];
        $user = self::getUser();
        if ($user->mobile) {
            $userinfo['mobile'] = $user->mobile;
        }
        if ($user->email) {
            $userinfo['email'] = $user->email;
        }
        $data['userinfo'] = $userinfo;
        if ($user_certificate == null) {
            //未实名验证
            $data['is_certificate'] = 0;
        } else {
            $data['is_certificate'] = 1;
            $data['name'] = $user_certificate->real_name;

            if ($user->role != ARUser::ROLE_AGENT) {
                $data['is_agent'] = 0;
            } else {
                $data['is_agent'] = 1;
                //获取经纪人额度
                $broker_amount = ARBrokerAmount::find()->where(['uid' => $user->id])->asArray()->all();
                $coinInfo = ARCoinType::find()->all();
                foreach ($broker_amount as $key => $value) {
                    $broker[$value['coin']] = $value;
                }
                $quota = [];
                foreach ($coinInfo as $row) {
                    if (isset($broker[$row->id])) {
                        $amount['coin'] = $row->name;
                        $amount['amount'] = $broker[$row->id]['amount'];
                        $amount['amount_used'] = $broker[$row->id]['amount_used'];
                        $quota[] = $amount;
                    }
                }
                $data['quota'] = $quota;
            }
        }

        return $data;
    }

    /**
     * 获取登陆地点
     */
    public function getIpPlace($ip)
    {
        if ($ip == '127.0.0.1' || $ip == '::1') {
            return '内网ip';
        }
        //新浪
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
        $result = self::curl($url);
        if ($result && is_array($result)) {
            $place = $result['country'] . $result['province'] . $result['city'];
            return $place;
        }
        //淘宝
        $url = "http://ip.taobao.com/service/getIpInfo.php?ip=$ip";
        $result = self::curl($url);
        if ($result && $result['code'] == 0) {
            $data = $result['data'];
            $place = $data['country'] . $data['region'] . $data['city'];
            return $place;
        }
        return '';
    }

    /**
     * ip列表
     */
    public function ipList()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $sql = ARLoginHistory::find()->where(['uid' => Yii::$app->user->id]);
        $count = $sql->count();
        $result = $sql->orderBy(['login_at' => SORT_DESC])->limit((int) $this->size)->offset(((int) $this->page - 1) * (int) $this->size)->all();
        $row = ArrayHelper::toArray($result, [
            ARLoginHistory::className() => [
                'ip',
                'login_time' => function ($row) {
                    return Yii::$app->formatter->asDatetime($row->login_at);
                },
                'place',
            ],
        ]);
        return ['count' => $count, 'row' => $row];
    }

    /**
     * 修改登录密码
     */
    public function editPassword()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $user = $this->getUser();
                $user->setPassword($this->password);

                if ($user->update() != false) {
                    $transaction->commit();
                    return true;
                } else {
                    self::getErrorMessge($user);
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }
    }

    /**
     * 修改邮箱
     */
    public function editEmail()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $user = $this->getUser();
            list($flag, $data) = Message::validateEmailCode('editemail', $this->code, $user->email);
            if (!$flag) {
                self::throwError('200008');
            }
            list($flag, $data) = Message::validateEmailCode('binding', $this->new_code, $this->new_email);
            if (!$flag) {
                self::throwError('200009');
            }
            $user->email = $this->new_email;
            $user->username = Yii::$app->params['modeType']['email'] . $this->new_email;
            if ($user->update() != false) {
                return ['email' => $this->new_email];
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 修改手机号码
     */
    public function editMobile()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $user = $this->getUser();
            list($flag, $data) = Message::validateMobileCode('editmobile', $this->code, $user->mobile);
            if (!$flag) {
                self::throwError('200005');
            }
            list($flag, $data) = Message::validateMobileCode('binding', $this->new_code, $this->new_mobile);
            if (!$flag) {
                self::throwError('200006');
            }

            $user->mobile = $this->new_mobile;
            $user->username = Yii::$app->params['modeType']['sms'] . $this->new_mobile;
            if ($user->update() != false) {
                return ['mobile' => $this->new_mobile];
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 绑定邮箱
     */
    public function setEmail()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $user = $this->getUser();
            list($flag, $data) = Message::validateEmailCode('binding', $this->code, $this->email);
            if (!$flag) {
                self::throwError('200004');
            }
            $user->email = $this->email;
            //$user->username = Yii::$app->params['modeType']['email'] . $this->email;
            if ($user->update() != false) {
                $userconfig = ARUserConfig::find()->where(['uid' => $user->id])->one();
                $userconfig->is_email = ARUserConfig::STATUS_BIND;
                $userconfig->update();
                return ['email' => $this->email];
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 设置手机号码
     */
    public function setMobile()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $user = $this->getUser();
            list($flag, $data) = Message::validateMobileCode('binding', $this->code, $this->mobile, $this->country);
            if (!$flag) {
                self::throwError('200004');
            }
            $user->mobile = $this->mobile;
            if ($user->update() != false) {
                $userconfig = ARUserConfig::find()->where(['uid' => $user->id])->one();
                $userconfig->is_mobile = ARUserConfig::STATUS_BIND;
                $userconfig->update();
                return ['mobile' => $this->mobile];
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 设置交易密码
     */
    public function setPayword()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $user = $this->getUser();
            if ($this->mode == Message::MODE_EMAIL) {
                //通过邮箱设置交易密码
                if (!$user->email) {
                    self::throwError('100013');
                }
                list($flag, $data) = Message::validateEmailCode('setpaywd', $this->code, $user->email);
            } else {
                if (!$user->mobile) {
                    self::throwError('100014');
                }
                list($flag, $data) = Message::validateMobileCode('setpaywd', $this->code, $user->mobile);
            }
            if (!$flag) {
                self::throwError('200004');
            }
            $user->payword_hash = Yii::$app->security->generatePasswordHash($this->payword);
            if ($user->update() != false) {
                $userconfig = ARUserConfig::find()->where(['uid' => $user->id])->one();
                $userconfig->is_payword = ARUserConfig::STATUS_BIND;
                $userconfig->update();
                return true;
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 修改交易密码
     */
    public function editPayword()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $user = $this->getUser();
                $user->payword_hash = Yii::$app->security->generatePasswordHash($this->payword, 6);
                if ($user->update() != false) {
                    $transaction->commit();
                    return true;
                } else {
                    self::getErrorMessge($user);
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }
    }

    /**
     * 设置登录密码(邮箱)
     */
    public function setPassword()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        } else {
            list($flag, $user) = Message::validateEmailToken($this->email, $this->token);
            if ($flag === -1) {
                self::throwError('100016');
            }
            if ($flag === -2) {
                self::throwError('100017');
            }
            if ($flag === -3) {
                self::throwError('100018');
            }
            $user->password_hash = Yii::$app->security->generatePasswordHash($this->password);
            if ($user->update() != false) {
                return true;
            } else {
                self::getErrorMessge($user);
            }
        }
    }

    /**
     * 设置登录密码(手机)
     */
    public function resetPassword()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $userinfo = ARUser::find()->where(['mobile' => $this->mobile])->one();
        if (!$userinfo) {
            self::throwError('100019');
        }
        list($flag, $data) = Message::validateMobileCode('findpasswd', $this->code, $this->mobile, $this->country);
        if (!$flag) {
            self::throwError('200004');
        }
        $userinfo->password_hash = Yii::$app->security->generatePasswordHash($this->password);
        if ($userinfo->update() != false) {
            return true;
        } else {
            self::getErrorMessge($userinfo);
        }
    }
    /**
     * 创建平台用户
     */
    public function createPlatform()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }

        $user = new ARUser();
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->role = ARUser::ROLE_PLATFORM;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                self::getErrorMessge($user);
            }
            $roleInfo = Yii::$app->authManager->getRole(self::ROLE_PLATFORM);
            if (empty($roleInfo)) {
                self::throwError('200002');
            }
            $auth = Yii::$app->authManager->assign($roleInfo, $user->id);
            if (!$auth) {
                self::throwError('200003');
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
        return ['userId' => $user->id, 'username' => $user->username];
    }

    /**
     * 创建管理员账户
     */
    public function addSystemer()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }

        $user = new ARUser();
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->role = ARUser::ROLE_ADMIN;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                self::getErrorMessge($user);
            }
            $roleInfo = Yii::$app->authManager->getRole(self::ROLE_SYSTEM);
            if (empty($roleInfo)) {
                self::throwError('200002');
            }
            $auth = Yii::$app->authManager->assign($roleInfo, $user->id);
            if (!$auth) {
                self::throwError('200003');
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
        return ['userId' => $user->id, 'username' => $user->username];
    }

    /**
     * 实名认证
     */
    public function certificate()
    {
        set_time_limit(20);
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $uid = Yii::$app->user->id;
        $usercertificate = ARUserCertificate::find()->where(['uid' => $uid])->one();
        if ($usercertificate) {
            self::throwError('700001');
        }
        $compareResult = Certificate::piccompare($this->image_mid, $this->image_mid_hand);
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if ($compareResult) {
                $newUserCertificate = new ARUserCertificate();
                $newUserCertificate->setScenario(ARUserCertificate::SCENARIO_ADD);
                $newUserCertificate->attributes = $this->attributes;
                $newUserCertificate->uid = $uid;
                if (!$newUserCertificate->save()) {
                    self::getErrorMessge($newUserCertificate);
                }
            
                $userconfig = ARUserConfig::find()->where(['uid' => $uid])->one();
                if($userconfig){
                    $userconfig->is_real = ARUserConfig::STATUS_BIND;
                    if(!$userconfig->update()){
                        self::getErrorMessge($userconfig);
                    }
                }
                $transaction->commit();
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
       
        return ['userId' => $uid, 'real_name' => $this->real_name];
    }

}
